package class04;

import utils.ListNode;

/**
 * @ClassName Code05_链表相加
 * @Description: 两个链表相加 力扣2
 * @Author: WangWenpeng
 */
public class Code05_链表相加 {

    // 求链表长度
    public static int listLength(ListNode head) {
        int len = 0;
        while (head != null) {
            len++;
            head = head.next;
        }
        return len;
    }

    //两个链表相加
    public static ListNode addTwoNumbers(ListNode head1, ListNode head2) {
        //拿到两个链表的长度  拿到长短链表的头结点
        int len1 = listLength(head1);
        int len2 = listLength(head2);
        ListNode longHead = len1 >= len2 ? head1 : head2;
        ListNode shortHead = longHead == head1 ? head2 : head1;

        //计算得数字修改长链表的值
        ListNode curL = longHead;
        ListNode curS = shortHead;
        ListNode last = curL;
        int carry = 0;
        int curNum = 0;
        // 长短链表都存在
        while (curS != null) {
            curNum = curL.value + curS.value + carry;
            curL.value = (curNum % 10);
            carry = curNum / 10;
            last = curL;
            curL = curL.next;
            curS = curS.next;
        }
        //只剩下了长链表
        while (curL != null) {
            curNum = curL.value + carry;
            curL.value = (curNum % 10);
            carry = curNum / 10;
            last = curL;
            curL = curL.next;
        }

        //最后还有就加一位
        if (carry != 0) {
            last.next = new ListNode(1);
        }
        return longHead;
    }
}
